package cn.itcast.www.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import cn.itcast.www.dao.IBaseJpaDao;

@Transactional
public class BaseJpaDaoImpl<T extends Serializable> implements IBaseJpaDao<T>{
	
	private Class<T> clazz;

	@PersistenceContext
	protected EntityManager entityManager;
	
	BaseJpaDaoImpl(){
		this.clazz = (Class<T>) ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public T findOne(Serializable id) {
		return entityManager.find(clazz, id);
	}

	public List<T> findAll() {
		return entityManager.createQuery("from " + clazz.getName()).getResultList();
	}

	public void create(T entity) {
		entityManager.persist(entity);
	}
	
	public T update(T entity) {
		return entityManager.merge(entity);
	}

	public void delete(T entity) {
		entityManager.remove(entity);
	}

	public void deleteById(Serializable entityId) {
		T entity = findOne(entityId);
		delete(entity);
	}

}
